package com.elves.auth.service;

import com.alibaba.excel.EasyExcel;
import com.elves.auth.entity.supplier.Supplier;
import com.elves.auth.entity.supplier.SupplierJpa;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.io.File;

@Service
@Slf4j
public class SupplierService {

    @Resource
    SupplierJpa supplierJpa;

    public void saveSuppliers(MultipartFile fileExcel) {
        List<Object> excelSupplier;
        try (InputStream inputStream = fileExcel.getInputStream()) {
            excelSupplier = EasyExcel.read(inputStream)
                    .sheet("供应商")
                    .doReadSync();
            log.info("读取到{}条供应商别数据", excelSupplier.size());
            for (int i = 0; i < excelSupplier.size(); i++) {
                Object obj = excelSupplier.get(i);
                log.info("{} excel supplier {} data:{}", i, obj.getClass(), obj);
                Supplier supplier = Supplier.mapToSupplier(CommonService.rowToMap(obj));
                if (supplier != null) {
                    supplierJpa.save(supplier);
                } else {
                    log.error("解析错误：{}:{}", i, obj);
                }
            }
        } catch (IOException e) {
            log.error("读取Excel文件“设备类别”sheet失败", e);
            throw new RuntimeException("读取Excel文件“设备类别”sheet失败", e);
        }
    }
}
